//
//  LineViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/7/27.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

import Charts

class SymbolsValueFormatter: NSObject,IAxisValueFormatter {
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        
        if value >= 1000 {
            return String(format: "%.0f", value / 1000) + "k"
        }
        
        return String(format: "%.0f", value)
        
    }
    
    
}

class LineViewController: BaseViewController {

    let _lineView = LineChartView.init(frame: CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - 300))
    
    override var names: Array<String>{
        return ["datas"]
    }
    
    override func path(for name: String) -> String {
        return ContractResolveDegree
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        return [:]
    }
    
    override func success(for name: String) -> NetSuccess {
        
        func suc(json: JSON)->Void{
            
            print(json)
            
            guard let _ = json.contents?["data"]?.contents else {
                self.alert("数据为空")
                return
            }
            
            guard let invoice = json["invoiceData"].array else { return  }
            
            let invoiceData = invoice.map { (json) -> Double in
                return json.double!
            }
            
            guard let backCapital = json["backCapitalData"].array else { return  }
            
            let backCapitalData = backCapital.map { (json) -> Double in
                return json.double!
            }
            
            guard let invoiceNoBackCapital = json["invoiceNoBackCapitalData"].array else { return  }
            
            let invoiceNoBackCapitalData = invoiceNoBackCapital.map { (json) -> Double in
                return json.double!
            }
            
            _lineView.data = setData(with: invoiceData, backCapitaData: backCapitalData, invoiceNoBackCapitalData: invoiceNoBackCapitalData)
            
        }
        
        return suc
    }
    
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        _lineView.backgroundColor =  .clear
        
        let l = _lineView.legend
        
        l.horizontalAlignment = .center
        
        l.verticalAlignment = .top
        
        l.orientation = .horizontal
        
        l.drawInside = false
        
        l.font = .systemFont(ofSize: 14, weight: .light)
        
        l.yOffset = 0
        
        l.xOffset = 10
        
        l.yEntrySpace = 0
        
        _lineView.chartDescription?.enabled = false
        
        _lineView.noDataText = "暂无数据";
        
        _lineView.scaleYEnabled = false;//取消Y轴缩放
        
        _lineView.doubleTapToZoomEnabled = false;//取消双击缩放
        
        _lineView.dragEnabled = false;//启用拖拽图标
        
        _lineView.dragDecelerationEnabled = false;//拖拽后是否有惯性效果
        
        _lineView.drawMarkers = true
        
        let markerView = LineMarker(color: UIColor.black.withAlphaComponent(0.5), font: UIFont.systemFont(ofSize: 12), textColor: .white, insets: UIEdgeInsets.zero)
        
        markerView.minimumSize = CGSize.init(width: 50, height: 30)
        
        markerView.chartView = _lineView
        
        _lineView.marker = markerView
        
        _lineView.dragDecelerationFrictionCoef = 0.9;//拖拽后惯性效果的摩擦系数(0~1)，数值
        
        self.view.addSubview(_lineView)
        
        _lineView.rightAxis.enabled = false
        
        let leftAxis = _lineView.leftAxis
        
        leftAxis.labelPosition = .outsideChart
        
        leftAxis.labelCount = 5
        
        leftAxis.axisLineColor = .hex("666666")
        
        leftAxis.gridAntialiasEnabled = true
        
        leftAxis.valueFormatter = SymbolsValueFormatter()
        
        let xAxis = _lineView.xAxis
        
        xAxis.labelPosition = .bottom
        
        xAxis.drawGridLinesEnabled = false
        
        _lineView.maxVisibleCount = 999
        
        _lineView.legend.enabled = true
        
        self.load(with: "datas")
        
    }
    
    func setData(with invoiceData:Array<Double>, backCapitaData:Array<Double>, invoiceNoBackCapitalData:Array<Double>) -> LineChartData {
        let xVals_count = 12
        
        var xVals: Array<String> = []
        
        for i in 0 ..< xVals_count {
            xVals.append(String(format: "%i月", i))
        }
        
        _lineView.xAxis.valueFormatter = DateValueFormatter()
        
        var yVals: Array<ChartDataEntry> = []
        
        for (index, value) in invoiceData.enumerated() {
            yVals.append(ChartDataEntry.init(x: Double(index), y: value))
        }
        
        var yVals2: Array<ChartDataEntry> = []
        
        for (index, value) in backCapitaData.enumerated() {
            yVals2.append(ChartDataEntry.init(x: Double(index), y: value))
        }
        
        var yVals3: Array<ChartDataEntry> = []
        
        for (index, value) in backCapitaData.enumerated() {
            yVals3.append(ChartDataEntry.init(x: Double(index), y: value))
        }
        
        var array: Array<LineChartDataSet> = []
        
        let set1 = LineChartDataSet.init(values: yVals, label: "开票")
        
        set1.mode = .horizontalBezier
        
        set1.drawValuesEnabled = false
        
        set1.circleColors = [UIColor.hex("f4c761")]
        
        set1.circleRadius = 3
        
        set1.circleHoleRadius = 2
        
        set1.lineWidth = 2.0 / UIScreen.main.scale
        
        set1.cubicIntensity = 0.01
        
        set1.valueColors = [UIColor.hex("f4c761")]
        
        set1.colors = [UIColor.hex("f4c761")]
        
        set1.fillColor = UIColor.hex("f4c761")
        
        set1.drawCirclesEnabled = true
        
        set1.drawFilledEnabled = true
        
        let set2 = LineChartDataSet.init(values: yVals2, label: "回款")
        
        set2.mode = .horizontalBezier
        
        set2.drawValuesEnabled = false
        
        set2.circleColors = [UIColor.hex("40eabc")]
        
        set2.circleRadius = 3
        
        set2.circleHoleRadius = 2
        
        set2.lineWidth = 2.0 / UIScreen.main.scale
        
        set2.cubicIntensity = 0.01
        
        set2.valueColors = [UIColor.hex("40eabc")]
        
        set2.colors = [UIColor.hex("40eabc")]
        
        set2.fillColor = UIColor.hex("40eabc")
        
        set2.drawCirclesEnabled = true
        
        set2.drawFilledEnabled = true
        
        let set3 = LineChartDataSet.init(values: yVals3, label: "开票未回款")
        
        set3.mode = .horizontalBezier
        
        set3.drawValuesEnabled = false
        
        set3.circleColors = [UIColor.hex("f46969")]
        
        set3.circleRadius = 3
        
        set3.circleHoleRadius = 2
        
        set3.lineWidth = 2.0 / UIScreen.main.scale
        
        set3.cubicIntensity = 0.01
        
        set3.valueColors = [UIColor.hex("f46969")]
        
        set3.colors = [UIColor.hex("f46969")]
        
        set3.fillColor = UIColor.hex("f46969")
        
        set3.drawCirclesEnabled = true
        
        set3.drawFilledEnabled = true
        
        array.append(set1)
        
        array.append(set2)
        
        array.append(set3)
        
        let data = LineChartData.init(dataSets: array)
        
        return data
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
